package com.ebelter.nb.ui.activitys;


import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ebelter.btcomlib.models.beans.UpdateVersionBean;
import com.ebelter.btcomlib.models.bluetooth.bean.ProductStyle;
import com.ebelter.btcomlib.models.bluetooth.products.nb.BondDevices;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.utils.AppUtils;
import com.ebelter.btcomlib.utils.BaseHandle;
import com.ebelter.btcomlib.utils.GsonUtils;
import com.ebelter.btcomlib.utils.NumUtils;
import com.ebelter.btcomlib.utils.SpUtil;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.activity_manager.ActivityManagers;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.btcomlib.views.dialogs.TextTipDialog;
import com.ebelter.nb.R;
import com.ebelter.nb.constants.NbConstants;
import com.ebelter.nb.interfaces.ISetJiGuanTagAlias;
import com.ebelter.nb.model.dao.DbUtils;
import com.ebelter.nb.model.http.HttpResponse2;
import com.ebelter.nb.model.http.MyStringCallback2;
import com.ebelter.nb.model.http.NbUpdateService;
import com.ebelter.nb.model.http.request.NbNetUtils;
import com.ebelter.nb.model.http.response.BandDeviceListResponse;
import com.ebelter.nb.model.http.response.Login_R;
import com.ebelter.nb.model.jg.JGMsgProcessor;
import com.ebelter.nb.model.jg.jgbean.JGBpmR;
import com.ebelter.nb.model.jg.jgbean.JGScaleR;
import com.ebelter.nb.model.nb.AMesuresCalBack;
import com.ebelter.nb.model.nb.NbManager;
import com.ebelter.nb.ui.fragments.BPM_Fragment;
import com.ebelter.nb.ui.fragments.Scale_Fragment;
import com.ebelter.nb.ui.view.Tip2Dialog;
import com.ebelter.nb.ui.view.UserSwitchPopupWindow;
import com.ebelter.nb.utils.NbUtitls;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


public class MainActivity extends NBBaseActivity implements View.OnClickListener {
    public static final String TAG = "MainActivity";

    public static final String GetBandListFromNet = "GetBandListFromNet";
    public static final String GetUserInfoFromNet = "GetUserInfoFromNet";
    public static final String WhichUser = "whichUser";

    private RelativeLayout m_topview_rl; //顶部标签的根布局
    private ImageView m_menu_iv;
    private TextView title_tv;

    //第一次进来提示用户的图片
    private ImageView first_input_iv;

    private LinearLayout m_top_bpm_ll;//血压计顶部人物选择框
    private TextView m_top_bpm_ll_name_tv;//血压计顶部人物选择框 下的名字

    private ImageView m_top_scale_iv;


    private DrawerLayout mDrawerLayout;
    private LinearLayout m_left_ll;


    private ProductStyle currentProductStyle = ProductStyle.NO;


    private BPM_Fragment mBPM_Fragment;
    private Scale_Fragment mScale_Fragment;


    private NbManager mNbManager;


    //血压计显示的用户几
    private int bmp_user_index = 1;
    private UserSwitchPopupWindow mUserSwitchPopupWindow;//用户选择弹框

    private static final int WHAT_GET_USERINFO_BANDLIST_FINISH = 44;
    private static final int WHAT_DISSMISS_NEWDATATIP = 45;

    private BaseHandle mBaseHandle;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        EventBus.getDefault().register(this);
        FV();
        closeOtherActivity();
        getNetVersion();
    }

    //检测服务器上的版本对比是不是需要更新
    public void getNetVersion() {
        if (NetUtils.available()) {
            final int verCode = AppUtils.getVersionCode(this);//获取当前版本号
            LogUtils.i(TAG, "verCode---" + verCode);
            NbNetUtils.getInstance().getUpdateVersionJson(this, new HttpResponse<UpdateVersionBean>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, UpdateVersionBean updateVersionBean, String s) {
                    LogUtils.i(TAG, "s---" + s);
                    if (isRequestSuccess && updateVersionBean != null) {

                        LogUtils.i(TAG, "服务器上的json--" + updateVersionBean.toString());
                        if (NumUtils.string2Int(updateVersionBean.getVerCode()) > verCode) {
                            showUpdateDialog(MainActivity.this, updateVersionBean);
                        }
                    }
                }
            });
        }
    }

    private TextTipDialog updateDialog;

    private void showUpdateDialog(Activity activity, final UpdateVersionBean mUpdateVersionBean) {
        if (activity == null || mUpdateVersionBean == null || activity.isFinishing() || activity.isDestroyed()) {
            return;
        }

        if (updateDialog != null) {
            updateDialog.cancel();
            updateDialog = null;
        }

        updateDialog = new TextTipDialog(activity, StringUtils.getResStr(R.string.New_version_is_available_touch_to_update));
        updateDialog.isPingBiBack = true;
        updateDialog.show();
        // dialog.setNativebtVisibility(View.GONE);
        updateDialog.setPositive_btBg(R.drawable.sp_s0176ff_r6);
        updateDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();
                update(mUpdateVersionBean);
            }
        });
    }

    //更新按钮
    private void update(UpdateVersionBean mUpdateVersionBean) {
        if (!NetUtils.available()) {
            ToastUtil.show(R.string.Network_error);
            return;
        }
        if (mUpdateVersionBean == null) {
            return;
        }
        Intent updateIntent = new Intent(this, NbUpdateService.class);
        updateIntent.putExtra(NbUpdateService.DownloadSer, mUpdateVersionBean);
        startService(updateIntent);
    }

    //关闭除主页外的其他界面
    public void closeOtherActivity() {
        ActivityManagers.getInstance().closeActivity(LoginActivity.TAG);
        ActivityManagers.getInstance().closeActivity(AddDeviceActivity.TAG);
        ActivityManagers.getInstance().closeActivity(AddDeviceResultActivity.TAG);
        ActivityManagers.getInstance().closeActivity(AddInfoActivity.TAG);
        ActivityManagers.getInstance().closeActivity(DeviceManagerActivity.TAG);
        ActivityManagers.getInstance().closeActivity(SetPswActivity.TAG);
    }

    private boolean getBandListFromNet;
    private boolean getUserInfoFromNet;

    @Override
    protected void initData() {
        super.initData();

        mUserSwitchPopupWindow = new UserSwitchPopupWindow(this);

        mNbManager = new NbManager(this);
        mNbManager.initJiGuanLoginInfo();//初始化极光信息
        mNbManager.startAutoCheck(10000);//5秒后检测机制运行 为了确保极光推送成功

        setListeners();
        isFirstOpen();
        dealBundle();
        updateScaleUserIcon();

        //showNewDataTip();
    }


    //处理bundle的机制
    private void dealBundle() {
        Bundle bundle = getIntentBundle();
        getBandListFromNet = bundle.getBoolean(MainActivity.GetBandListFromNet, false);
        getUserInfoFromNet = bundle.getBoolean(MainActivity.GetUserInfoFromNet, false);
        int whichUser = bundle.getInt(MainActivity.WhichUser, 0);
        if (whichUser == 1) {
            switProduct(ProductStyle.SCALE, false);
        }

        LogUtils.i(TAG, "-----getBandListFromNet = " + getBandListFromNet + "----getUserInfoFromNet = " + getUserInfoFromNet);

        if (getUserInfoFromNet && getBandListFromNet) {
            login();
        } else {
            mBaseHandle.sendEmptyMessage(WHAT_GET_USERINFO_BANDLIST_FINISH);
        }
    }

    private void login() {
        String phone = UserSpUtil.readString(NbConstants.User.phone);
        String pswMd5 = UserSpUtil.readString(NbConstants.User.wsp);
        showLoadingDialog("正在登录...");
        NbNetUtils.getInstance().login(this, phone, pswMd5, new HttpResponse2<Login_R>() {
            @Override
            public void result(boolean isRequestSuccess, String requestResultDesc, int requestResultCode, Login_R login_r, String s) {

                LogUtils.i(TAG, "--login--" + s);
                if (isRequestSuccess) {

                    if (login_r != null && login_r.resultMessage != null) {

                        if (requestResultCode == MyStringCallback2.SUCCESS) {
                            LogUtils.i(TAG, "--login--成功");
                            saveUserData(login_r);
                            updateScaleUserIcon();
                            getBandDeviceFromNet(login_r.resultMessage.phone);
                        } else {
                            ToastUtil.show(login_r.message);
                            loginFailureGo2LoginActivity();
                        }

                    } else {
                        ToastUtil.show("登录失败");
                        loginFailureGo2LoginActivity();
                    }


                } else {
                    ToastUtil.show("登录失败");
                    loginFailureGo2LoginActivity();
                }
            }
        });
    }

    private void loginFailureGo2LoginActivity() {
        LogUtils.i(TAG, "--login--失败");
        UserSpUtil.writeString(NbConstants.User.wsp, null);
        startActivity(LoginActivity.class);
        finish();
    }

    private void getBandDeviceFromNet(final String user_id) {

        NbNetUtils.getInstance().getUserBandList(this, user_id, new HttpResponse<BandDeviceListResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BandDeviceListResponse bandDeviceListResponse, String s) {
                LogUtils.i(TAG, "----getUserBandList--" + s);
                LogUtils.i("getUserBandList", TAG + "----getUserBandList--" + s);
                if (isRequestSuccess && bandDeviceListResponse != null && bandDeviceListResponse.status == 0) {
                    LogUtils.i(TAG, "--getUserBandList--成功");
                    if (bandDeviceListResponse.data != null) {
                        DbUtils.deleteTable(BondDevices.class);//先删除掉
                        for (int i = 0; i < bandDeviceListResponse.data.size(); i++) {
                            BandDeviceListResponse.DataBean dataBean = bandDeviceListResponse.data.get(i);
                            BondDevices bondDevices = new BondDevices();
                            bondDevices.user_id = user_id;
                            bondDevices.type = dataBean.type;
                            bondDevices._id = dataBean.id;//序列号
                            bondDevices.sn_number = dataBean.sn_number;
                            bondDevices.device_id = dataBean.device_id;//设备的IMEI码
                            bondDevices.create_time = dataBean.create_time;//创建的时间
                            bondDevices.save();
                        }
                    }

                    dissLoadingDialog();

                    if (mBaseHandle != null)
                        mBaseHandle.sendEmptyMessage(WHAT_GET_USERINFO_BANDLIST_FINISH);


                } else {
                    LogUtils.i(TAG, "--getUserBandList--失败");
                    loginFailureGo2LoginActivity();
                }


            }
        });

    }

    //保存用户数据
    private void saveUserData(Login_R login_r) {
        //这里不需要判断了对象是否为空了 前面已经判断过了
        UserSpUtil.writeString(NbConstants.User.authkey, login_r.resultMessage.authkey);
        UserSpUtil.writeString(NbConstants.User.phone, login_r.resultMessage.phone);
        UserSpUtil.writeString(NbConstants.User.birthday, login_r.resultMessage.birthday);//yyyy-MM-dd
        UserSpUtil.writeString(NbConstants.User.email, login_r.resultMessage.email);
        UserSpUtil.writeString(NbConstants.User.name, login_r.resultMessage.name);
        UserSpUtil.writeInt(NbConstants.User.height, NumUtils.string2Int(login_r.resultMessage.height));
        UserSpUtil.writeFloat(NbConstants.User.weight, NumUtils.string2Float(login_r.resultMessage.weight));
        UserSpUtil.writeInt(NbConstants.User.sex, NumUtils.string2Int(login_r.resultMessage.sex));
        UserSpUtil.writeInt(NbConstants.User.profession, login_r.resultMessage.profession);//0普通 1运动员
        UserSpUtil.writeString(NbConstants.User.modifydate, login_r.resultMessage.modifydate);
    }


    //检测是否第一次进入这个app
    private void isFirstOpen() {
        boolean isFirstOpenMainActvity = SpUtil.readBoolean(NbConstants.System.isFirstOpenMainActvity, true);

        ProductStyle nextDisplayProductStyle = ProductStyle.BPM;
        boolean isBondBpmDevice = NbUtitls.isBondBpmDevice();
        boolean isBondScaleDevice = NbUtitls.isBondScaleDevice();
        int lastDisplay = NbUtitls.getLastDisplayFragment();

        if (isBondBpmDevice && !isBondScaleDevice) {//只绑定了血压计
            nextDisplayProductStyle = ProductStyle.BPM;
        } else if (!isBondBpmDevice && isBondScaleDevice) {//只绑定了体脂秤
            nextDisplayProductStyle = ProductStyle.SCALE;
        } else {
            //可能两个都没绑定或者两个都绑定了
            nextDisplayProductStyle = (lastDisplay == 0 ? ProductStyle.BPM : ProductStyle.SCALE);
        }


        if (isFirstOpenMainActvity) {
            ViewUtils.displayView(first_input_iv);//显示引导图片
            clickTopMenu();
            switProduct(nextDisplayProductStyle, true);
        } else {
            switProduct(nextDisplayProductStyle, false);
        }
    }

    private void setListeners() {

        m_menu_iv.setOnClickListener(this);
        first_input_iv.setOnClickListener(this);
        m_top_bpm_ll.setOnClickListener(this);
        m_top_scale_iv.setOnClickListener(this);

        mNbManager.setMesuresCalBack(new AMesuresCalBack() {
            @Override
            public void connectError(ProductStyle productStyle) {
                showBandDialog(productStyle);
            }

            @Override
            public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
            }

            @Override
            public void onDisConnected(ProductStyle productStyle) {
                super.onDisConnected(productStyle);
            }
        });

        mUserSwitchPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ViewUtils.displayView(m_top_bpm_ll);
                StatusBarUtil.setColor(MainActivity.this, Color.parseColor("#00333333"), 0);
            }
        });
        //用户选择切换popView
        mUserSwitchPopupWindow.setmSelectListener(new UserSwitchPopupWindow.SelectListener() {
            @Override
            public void select(boolean isChange, int index) {
                LogUtils.i(TAG, "---isChange = " + isChange + "---index = " + index);
                if (isChange) {
                    ViewUtils.setTextViewStr(m_top_bpm_ll_name_tv, index == 1 ? "用户1" : "用户2");
                    bmp_user_index = index;
                    updateBmpDataByUserIndex();
                }
            }
        });

        mBaseHandle = new BaseHandle(this);
        mBaseHandle.setMsgCallBack(new BaseHandle.IHandleMsgCallBack() {
            @Override
            public void handleMsg(Message msg) {
                dealHandleMsg(msg);
            }
        });

        mNbManager.setmISetJiGuanTagAlias(new ISetJiGuanTagAlias() {
            @Override
            public void success() {
                LogUtils.i(TAG, "设置极光tag 成功");
            }

            @Override
            public void failure() {
                LogUtils.i(TAG, "设置极光tag 失败");
            }
        });
    }


    //处理Handle信息
    private void dealHandleMsg(Message msg) {
        if (msg.what == WHAT_GET_USERINFO_BANDLIST_FINISH) {
            LogUtils.i(TAG, "-handle-收到-WHAT_GET_USERINFO_BANDLIST_FINISH-");
            sendUserInfo2Scale();
        } else if (msg.what == WHAT_DISSMISS_NEWDATATIP) {
            if (mNewDataTipDialog != null) mNewDataTipDialog.dismiss();
        }
    }

    //准备下发用户信息给体脂秤
    private void sendUserInfo2Scale() {

        if (!NetUtils.available()) {
            return;
        }

        String userid = NbUtitls.getLoginUserId();
        BondDevices scaleDevices = NbUtitls.getBondScaleDevice();
        String birthday = UserSpUtil.readString(NbConstants.User.birthday);//yyyy-MM-dd
        int height = UserSpUtil.readInt(NbConstants.User.height);
        if (height <= 0) {
            LogUtils.i(TAG, "信息完整 发现height小于0 改为168");
            height = 168;
        }

        int age = NbUtitls.getAge();
        float weight = UserSpUtil.readFloat(NbConstants.User.weight);

        if (weight <= 0) {
            LogUtils.i(TAG, "信息完整 发现weight小于0 改为52");
            weight = 52;
        }

        int profession = UserSpUtil.readInt(NbConstants.User.profession, 0);


        int sex = UserSpUtil.readInt(NbConstants.User.sex);

        LogUtils.i(TAG, "--下发用户信息给体脂秤-sendUserInfo2Scale--userid=" + userid + "--scaleDevices=" + scaleDevices +
                "--birthday=" + birthday + "--height=" + height + "--weight=" + weight + "--sex=" + sex + "--profession=" + profession);

        if (!TextUtils.isEmpty(userid) && scaleDevices != null && !TextUtils.isEmpty(birthday) && height > 0 && weight >= 0 && sex >= 0) {
            LogUtils.i(TAG, "信息完整 准备下发给秤");

            weight = NumUtils.numBaoLiuWei1(weight);

            NbNetUtils.getInstance().sendUserInfo2Scale(this, userid, scaleDevices.device_id, age, height, weight, sex,
                    profession, new HttpResponse<BandDeviceListResponse>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, BandDeviceListResponse response, String s) {
                    LogUtils.i(TAG, "--sendUserInfo2Scale--" + s);
                    if (isRequestSuccess && response != null && response.status == 0) {
                        LogUtils.i(TAG, "--下发用户信息给秤--成功");
                    } else {
                        LogUtils.i(TAG, "--下发用户信息给秤--失败");
                    }
                }
            });


        } else {
            LogUtils.i(TAG, "信息不完整 下发给秤指令 终止");
        }


    }


    private TextTipDialog textTipDialog;

    //展示绑定的提示框
    private void showBandDialog(ProductStyle productStyle) {
        if (textTipDialog != null && textTipDialog.isShowing()) {
            return;
        }

        if (textTipDialog != null && !textTipDialog.isShowing()) {
            textTipDialog.show();
        } else {
            textTipDialog = new TextTipDialog(this, "请先绑定设备");
            textTipDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
                @Override
                public void cancel(Dialog dialogView) {
                    dialogView.cancel();
                    checkInfo();//当没有显示绑定设备对话框的时候就要去检测一下用户信息了
                }

                @Override
                public void ok(Dialog dialogView) {
                    dialogView.cancel();
                    Intent addDeviceIntent = new Intent(MainActivity.this, AddDeviceActivity.class);
                    startActivityForResult(addDeviceIntent, AddDeviceActivity.requestCode);
                }
            });
            textTipDialog.show();
            textTipDialog.setTextColor(1, 0xff464646);
            textTipDialog.setTittleDrawableLeft(R.drawable.ic_warring);
            textTipDialog.setNative_btBg(R.drawable.sp_scccccc_r6);
            textTipDialog.setPositive_btBg(R.drawable.sp_s0176ff_r6);
            textTipDialog.setPositiveText("绑定");
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (textTipDialog == null || !textTipDialog.isShowing()) {
            checkInfo();//当没有显示绑定设备对话框的时候就要去检测一下用户信息了
        }
    }

    private TextTipDialog addInfoDialog;


    //如果此时显示的是体脂秤 就去检测信息是否完全
    private void checkInfo() {
        //说明当前的设备绑定了
        if (currentProductStyle == ProductStyle.SCALE) {
            //如果当前的是体脂秤的还有检测一下是否信息补全了
            boolean isWQ = NbUtitls.infoIsWanQuan();
            if (isWQ) {//信息完全 退出
                return;
            }
            if (addInfoDialog != null && addInfoDialog.isShowing()) {
                return;
            }

            if (addInfoDialog != null && !addInfoDialog.isShowing()) {
                addInfoDialog.show();
            } else {
                addInfoDialog = new TextTipDialog(this, "请先补全信息");
                addInfoDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
                    @Override
                    public void cancel(Dialog dialogView) {
                        dialogView.cancel();
                    }

                    @Override
                    public void ok(Dialog dialogView) {
                        dialogView.cancel();
                        Intent addDeviceIntent = new Intent(MainActivity.this, AddInfoActivity.class);
                        startActivityForResult(addDeviceIntent, AddInfoActivity.requestCode);
                    }
                });
                addInfoDialog.show();
                addInfoDialog.isPingBiBack = true;
                addInfoDialog.setNativebtVisibility(View.GONE);
                addInfoDialog.setTextColor(1, 0xff464646);
                addInfoDialog.setTittleDrawableLeft(R.drawable.ic_warring);
                addInfoDialog.setNative_btBg(R.drawable.sp_scccccc_r6);
                addInfoDialog.setPositive_btBg(R.drawable.sp_s0176ff_r6);
            }

        }
    }

    private void FV() {
        m_topview_rl = findViewById(R.id.m_topview_rl);

        m_menu_iv = findViewById(R.id.m_menu_iv);
        ViewUtils.setImageResource(m_menu_iv, R.drawable.ic_menu);
        title_tv = findViewById(R.id.m_title_tv);


        m_top_bpm_ll = findViewById(R.id.m_top_bpm_ll);
        m_top_bpm_ll_name_tv = findViewById(R.id.m_top_bpm_ll_name_tv);

        m_top_scale_iv = findViewById(R.id.m_top_scale_iv);

        mDrawerLayout = findViewById(R.id.drawer_layout);
        m_left_ll = findViewById(R.id.m_left_ll);

        first_input_iv = findViewById(R.id.first_input_iv);
    }

    //更新显示用户图标的男女信息
    private void updateScaleUserIcon() {
        if (NbUtitls.getSex() == 1) {
            ViewUtils.setImageResource(m_top_scale_iv, R.drawable.ic_man);
        } else {
            ViewUtils.setImageResource(m_top_scale_iv, R.drawable.ic_man);
        }
    }


    /**
     * 切换设备
     *
     * @param productStyle  设备类型
     * @param isOnlyDisplay 是否只是显示 如果为false 逻辑也要相对应的显示
     */
    private void switProduct(ProductStyle productStyle, boolean isOnlyDisplay) {
//        if (currentProductStyle == productStyle) {
//            return;
//        }

        currentProductStyle = productStyle;
        if (textTipDialog != null) textTipDialog.dismiss();

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideAllFragment(transaction, mBPM_Fragment, mScale_Fragment);

        int contain = R.id.m_m_c_fl;//容器

        if (productStyle == ProductStyle.BPM) {
            //ViewUtils.setTextViewStr(title_tv, "血压");
            //  setTopTitleStr("血压");
            if (mBPM_Fragment == null) {
                mBPM_Fragment = new BPM_Fragment();
                transaction.add(contain, mBPM_Fragment);
            } else {
                transaction.show(mBPM_Fragment);
            }
            UserSpUtil.writeInt(NbConstants.System.LastDisplayFragment, 0);//记录最后显示的fragment变量

            ViewUtils.displayView(m_top_bpm_ll);//显示血压计顶部框
            ViewUtils.hideView(m_top_scale_iv);//隐藏体脂秤图像框
            updateTopTitleStr(productStyle);
        } else {
            //ViewUtils.setTextViewStr(title_tv, );
            // setTopTitleStr("体脂秤");
            if (mScale_Fragment == null) {
                mScale_Fragment = new Scale_Fragment();
                transaction.add(contain, mScale_Fragment);
            } else {
                transaction.show(mScale_Fragment);
            }

            UserSpUtil.writeInt(NbConstants.System.LastDisplayFragment, 1);//记录最后显示的fragment变量

            ViewUtils.displayView(m_top_scale_iv);//显示体脂秤图像框
            ViewUtils.hideView(m_top_bpm_ll);//隐藏血压计顶部框
            updateTopTitleStr(productStyle);
        }
        transaction.commitAllowingStateLoss();//zcq20191126这里改过

        if (!isOnlyDisplay) {
            if (mNbManager != null) mNbManager.switchingEquipment(currentProductStyle);
        }
        checkInfo();//如果此时显示的是体脂秤 就去检测信息是否完全
    }


    private void setTopTitleStr(String str) {
        ViewUtils.setTextViewStr(title_tv, str);
    }

    @Override
    protected boolean isOpenBlueStationListener() {
        return true;//打开蓝牙监听器的意思
    }

    @Override
    protected void bluetoothStationReceive(Intent intent, String action) {
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    ToastUtil.show("蓝牙已关闭，请打开蓝牙");//打开蓝牙提示语
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    break;
                case BluetoothAdapter.STATE_ON:
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.m_menu_iv) {//顶部菜单
            clickTopMenu();
        } else if (vid == R.id.first_input_iv) {//第一次进入的图片提示框

            ViewUtils.goneView(first_input_iv);
            SpUtil.writeBoolean(NbConstants.System.isFirstOpenMainActvity, false);
            switProduct(ProductStyle.BPM, false);

        } else if (vid == R.id.m_top_bpm_ll) {
            m_top_bpm_ll_Click();//顶部血压计的图片切换

        } else if (vid == R.id.m_top_scale_iv) {
            Intent intent = new Intent(this, PersonInfoActivity.class);
            startActivityForResult(intent, PersonInfoActivity.REQUEST_CODE);
        }
    }


    //血压计顶部用户图标点击事件
    private void m_top_bpm_ll_Click() {
        ViewUtils.hideView(m_top_bpm_ll);
        StatusBarUtil.setColor(this, Color.parseColor("#88333333"), 0);
        if (mUserSwitchPopupWindow != null)
            mUserSwitchPopupWindow.show(getBaseContext(), m_topview_rl, bmp_user_index);
    }


    //点击了顶部菜单栏
    private void clickTopMenu() {
        if (mDrawerLayout != null) {
            if (mDrawerLayout.isDrawerOpen(m_left_ll)) {
                mDrawerLayout.closeDrawer(m_left_ll);
            } else {
                mDrawerLayout.openDrawer(m_left_ll);
            }
        }
    }

    //侧边栏-血压
    public void m_left_ll_xueya(View view) {
        switProduct(ProductStyle.BPM, false);
        clickTopMenu();
    }

    //侧边栏-体脂秤
    public void m_left_ll_tizhichen(View view) {
        switProduct(ProductStyle.SCALE, false);
        clickTopMenu();
    }

    //侧边栏-设备管理
    public void m_left_ll_shbgl(View view) {
        //startActivity(DeviceManagerActivity.class);
        Intent intent = new Intent(this, DeviceManagerActivity.class);
        startActivityForResult(intent, DeviceManagerActivity.RequestCode);
    }

    //侧边栏-关于
    public void m_left_ll_about(View view) {
        startActivity(AboutActivity.class);
    }

    //侧边栏-退出
    public void m_left_ll_exit(View view) {
        TextTipDialog textTipDialog = new TextTipDialog(this, StringUtils.getResStr(R.string.exit_tip));
        textTipDialog.setListener(new TextTipDialog.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView) {
                dialogView.cancel();

                String phone = UserSpUtil.readString(NbConstants.User.phone);
                UserSpUtil.removeAll();
                UserSpUtil.writeString(NbConstants.User.phone, phone);
                DbUtils.deleteTable(BondDevices.class);
                startActivity(LoginActivity.class);
                finish();
            }
        });
        textTipDialog.show();
        textTipDialog.setTextColor(1, 0xff464646);
        //  textTipDialog.setTextColor(2,0xff464646);
        textTipDialog.setNative_btBg(R.drawable.sp_scccccc_r6);
        textTipDialog.setPositive_btBg(R.drawable.sp_s0176ff_r6);
    }

    //侧边栏-测试按钮
    public void m_left_ll_ceshi(View view) {

//        增加了血压计imei---867726030108320
//        增加了体脂秤imei---867726033380785
//        增加了alias---13826672468
//        线程Name = main # code=0--alias = szebelter

//        JGBpmR jgBpmR = new JGBpmR();
//        JGBpmR.DeviceInfoBean d = new JGBpmR.DeviceInfoBean();
//        d.user="1";
//        d.time= TimeUtils.getCurrentTime1();
//        d.imei="867726030108320";
//        d.ano="0";
//        d.sys=((int)NumUtils.randomF(70,130))+"";
//        d.dia=((int)NumUtils.randomF(50,85))+"";
//        d.pul=((int)NumUtils.randomF(70,100))+"";
//        jgBpmR.deviceInfo=d;
//        JGMsgProcessor.getInstance().dealBpm(GsonUtils.getInstance().getGson().toJson(jgBpmR));


        JGScaleR jgScaleR = new JGScaleR();
        jgScaleR.deviceType = 1;
        JGScaleR.DeviceInfoBean d2 = new JGScaleR.DeviceInfoBean();
        d2.time = TimeUtils.getCurrentTime1();
        d2.imei = "867726033380785";
        d2.fat = ((int) NumUtils.randomF(200, 300)) + "";
        d2.resistor = ((int) NumUtils.randomF(300, 500)) + "";
        d2.weight = (NumUtils.numBaoLiuWei0(NumUtils.randomF(500, 700))) + "";
        d2.hart = ((int) NumUtils.randomF(60, 100)) + "";

        d2.usermode = 0;
        jgScaleR.deviceInfo = d2;
        JGMsgProcessor.getInstance().dealScale(this, GsonUtils.getInstance().getGson().toJson(jgScaleR));


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mNbManager != null) {
            mNbManager.exit();
            mNbManager = null;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommonEventBus event) {
        if (!event.whichReceive.contains(TAG)) {
            return;
        }
        LogUtils.i(TAG, "MainActivity--onEventMainThread接收到CommonEventBus信息--" + event.toString());

        if (TextUtils.equals(JGMsgProcessor.TAG, event.from)) {
            //收到测量数据的意思 切换到界面并且显示出来
            if (JGMsgProcessor.CMD_BPM == event.cmd) {
                switProduct(ProductStyle.BPM, true);
                disBpmData((JGBpmR) event.content);//收到极光推送 推过来的血压计信息
                showNewDataTip();//展示新数据来了的对话框
            } else if (JGMsgProcessor.CMD_SCALE == event.cmd) {
                switProduct(ProductStyle.SCALE, true);
                disScaleData((JGScaleR) event.content);//收到极光推送 推过来的体脂秤信息
                showNewDataTip();//展示新数据来了的对话框
            } else if (JGMsgProcessor.CMD_SCALE_SENDINFO2SERVICES == event.cmd) {
                sendUserInfo2Scale();
            }

        } else if (TextUtils.equals(AddDeviceResultActivity.TAG, event.from) && event.cmd == 10) {
            if (textTipDialog != null) {
                LogUtils.i(TAG, "---------关闭了对话框");
                textTipDialog.cancel();
                textTipDialog = null;
            }

        } else if (event.cmd == 88) {//更新顶部标题的指令

            updateTopTitleStr(currentProductStyle);
        }


    }

    //更新顶部标题的指令
    private void updateTopTitleStr(ProductStyle productStyle) {
        if (productStyle == ProductStyle.SCALE) {
            if (mScale_Fragment != null) {
                setTopTitleStr(mScale_Fragment.getTitleStr());
            }
        } else if (productStyle == ProductStyle.BPM) {
            if (mBPM_Fragment != null) {
                setTopTitleStr(mBPM_Fragment.getTitleStr());
            }
        }

    }

    private Tip2Dialog mNewDataTipDialog;

    private void showNewDataTip() {
        if (mNewDataTipDialog == null) {
            mNewDataTipDialog = new Tip2Dialog(this, "收到新的测量数据");
        }
        if (mBaseHandle != null) {
            mNewDataTipDialog.show();
            mBaseHandle.sendEmptyMessageDelayed(WHAT_DISSMISS_NEWDATATIP, 2000);
        }


    }

    private void disScaleData(JGScaleR jGScaleR) {
        if (jGScaleR == null || jGScaleR.deviceInfo == null) return;
        if (mScale_Fragment != null) {
            //先隐藏掉用户选择框
            mScale_Fragment.setScaleData(jGScaleR);

        }
    }


    //显示血压计数据
    private void disBpmData(JGBpmR jGBpmR) {
        if (jGBpmR == null || jGBpmR.deviceInfo == null) return;

        if (mBPM_Fragment != null) {
            //先隐藏掉用户选择框
            if (mUserSwitchPopupWindow != null && mUserSwitchPopupWindow.isShowing()) {
                mUserSwitchPopupWindow.dismiss();
            }
            int userIndex = NumUtils.string2Int(jGBpmR.deviceInfo.user);
            bmp_user_index = userIndex;
            ViewUtils.setTextViewStr(m_top_bpm_ll_name_tv, userIndex == 1 ? "用户1" : "用户2");

            mBPM_Fragment.setBpmData(jGBpmR);
            updateBmpDataByUserIndex();


        }
    }

    //显示相对应的用户测量数据
    public void updateBmpDataByUserIndex() {
        if (mBPM_Fragment != null) {
            mBPM_Fragment.disUserData(bmp_user_index);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.i(TAG, "onActivityResult-requestCode=" + requestCode + "---resultCode=" + resultCode);
        if (requestCode == AddInfoActivity.requestCode) {//补全信息界面回来
            LogUtils.i(TAG, "onActivityResult-补全信息界面回来");
            if (addInfoDialog != null && addInfoDialog.isShowing()) {
                addInfoDialog.cancel();
            }//如果此对话框已经显示就先关闭掉
            checkInfo();
            if (NbUtitls.infoIsWanQuan() && resultCode == 2) {
                sendUserInfo2Scale();
                updateScaleUserIcon();
            }
        } else if (resultCode == AddDeviceActivity.requestCode) {//绑定设备界面回来
            LogUtils.i(TAG, "onActivityResult-绑定设备界面回来");
            if (mNbManager != null) mNbManager.initJiGuanLoginInfo();
        } else if (requestCode == DeviceManagerActivity.RequestCode) {
            LogUtils.i(TAG, "onActivityResult-设备管理界面回来");
            if (mNbManager != null) mNbManager.initJiGuanLoginInfo();
        } else if (requestCode == PersonInfoActivity.REQUEST_CODE && resultCode == 2) {
            LogUtils.i(TAG, "onActivityResult-修改用户信息界面回来");
            sendUserInfo2Scale();
            updateScaleUserIcon();
        }

    }
}
